
/**
*
* @description : 信用修复发起
* @descriptionDetail : 信用修复发起-FJ
* @copyright : 浙江烟草
* @author : zx
* @create : 2024-05-14 10:10:13
*/
<template>
  <view class="page">
    <!-- #ifndef H5-DINGDING -->
    <theme-navbar :is-white="false" :title="currentTitle" :custom-back="goBack" style="z-index: 99999"></theme-navbar>
    <!-- #endif -->
    <view class="content">
      <u-form :rules="rules" ref="uForm" :model="baseInfo" label-position="top" label-width="auto">
        <form-section title="基础信息"></form-section>
        <u-form-item label="修复类型">
          <u-radio-group v-model="baseInfo.repairType" @change="radioGroupChange">
            <u-radio v-for="item, index in dictList" :key="index" :label="item.label" :name="item.value" :disabled="AddOrEdit=='edit'||isDisabled">{{ item.label }}</u-radio>
          </u-radio-group>
        </u-form-item>
        <u-form-item label="许可证号" prop="licNo" :required="true">
          <u-input placeHolder="" type="text" :disabled="true" v-model="baseInfo.licNo"></u-input>
          <u-button type="primary" size="mini" @click="handleGoToRetList" :disabled="isDisabled">
            选择
          </u-button>
        </u-form-item>
        <u-form-item label="申请人">
          <u-input placeHolder="" type="text" :disabled="true" v-model="baseInfo.applicant"></u-input>
        </u-form-item>
        <u-form-item label="申请时间">
          <!-- <u-input :disabled="true" input-align="left" placeholder="请选择日期" v-model="baseInfo.applyDate" @click="()=>{ !isDisabled &&goShowRegDate()}" /> -->
          <u-input :disabled="true" input-align="left" placeholder="请选择日期" v-model="baseInfo.applyDate" />
            
         </u-form-item>

        <u-form-item label="企业（字号）名称">
          <u-input placeHolder="" type="text" :disabled="true" v-model="baseInfo.companyName"></u-input>
        </u-form-item>
        <u-form-item label="统一社会信用代码">
          <u-input placeHolder="" type="text" :disabled="true" v-model="baseInfo.businessLicNo"></u-input>
        </u-form-item>
        <u-form-item label="负责人">
          <u-input placeHolder="" type="text" :disabled="true" v-model="baseInfo.managerName"></u-input>
        </u-form-item>
        <u-form-item label="涉烟违法违规行为" prop="targetName" :required="true">
          <u-input placeHolder="" type="textarea" :disabled="true" v-model="baseInfo.targetName"></u-input>
          <u-button type="primary" size="mini" @click="handleGoToTobacco" :disabled="isDisabled">
            选择
          </u-button>
        </u-form-item>
        <u-form-item label="扣分值">
          <u-input placeHolder="" type="text" :disabled="true" v-model="baseInfo.repairScore"></u-input>
        </u-form-item>
        <u-form-item label="信用等级">
          <u-input placeHolder="" type="text" :disabled="true" v-model="baseInfo.repairBeforeCreditLevel"></u-input>
        </u-form-item>
        <u-form-item label="信用分值">
          <u-input placeHolder="" type="text" :disabled="true" v-model="baseInfo.repairBeforeCreditScore"></u-input>
        </u-form-item>
        <u-form-item label="问题描述" prop="problemDescription" :required="true">
          <u-input placeHolder="" type="textarea" :disabled="isDisabled" v-model="baseInfo.problemDescription"></u-input>
        </u-form-item>
        <u-form-item label="核查情况" prop="checkResult" :required="true">
          <u-input placeHolder="" type="textarea" :disabled="isDisabled" v-model="baseInfo.checkResult"></u-input>
        </u-form-item>
        <u-gap :marginRight="getGapMarginRowNumber()" :marginLeft="getGapMarginRowNumber()" :height="$theme.cm_section_top_gap_height" :bg-color="$theme.cm_gap_color"></u-gap>
       <form-section title="附件列表"></form-section>
        <u-form-item label-position="top" label="图片信息" v-if="AddOrEdit!=='view'">
          <view class="zk-img-content">
            <m-upload :deletable="true" :maxCount="picIds" width="150rpx" height="150rpx" :disabled="isDisabled" :file-list="fileList" :multiple="true" index="fileList"
              :uploadParam="{'fiGroupCode':$FILE_GROUP_TYPE.m_credit_apply, }" upApiUrl="uploadBase64ForApp" ref="filePicUpload" @on-list-change="changeUpload"></m-upload>
          </view>
        </u-form-item>
        <scroll-view v-else :scroll-y="false" :scroll-x="true" :style="{ height: scrollRealHeight, marginTop: '5px', paddingBottom: '10px' }">
          <u-table class="tb-lay" ref="tbRef" style="width:100vw">
            <u-tr>
              <u-th width="10%">序列</u-th>
              <u-th width="55%">文件名</u-th>
              <u-th width="20%">大小</u-th>
              <u-th width="20%">状态</u-th>
            </u-tr>
            <u-tr v-for="(it, index) in dataSource" :key="'ds' + index">
              <u-td width="10%">{{ index + 1 }}</u-td>
              <u-td width="55%"><text class="td-text">{{ it.gfiStoreName || '&nbsp;' }}</text></u-td>
              <u-td width="20%"><text class="td-text">{{ it.gfiSize || '&nbsp;' }}</text></u-td>
              <u-td width="20%"><text class="td-text">上传成功</text></u-td>
            </u-tr>
          </u-table>
        </scroll-view>

        <!-- 附件列表结束 -->

        <!-- 承办人意见 -->
        <u-gap :marginRight="getGapMarginRowNumber()" :marginLeft="getGapMarginRowNumber()" :height="$theme.cm_section_top_gap_height" :bg-color="$theme.cm_gap_color"></u-gap>
        <form-section title="承办人意见"></form-section>
        <u-form-item label="">
          <u-input placeHolder="" type="textarea" :disabled="isDisabled" v-model="baseInfo.handlePersonAdvice"></u-input>
        </u-form-item>
        <u-form-item label="签名">
          <u-input placeHolder="" type="text" disabled v-model="baseInfo.handlePerson"></u-input>
        </u-form-item>
        <u-form-item label="承办时间">
          <u-input placeHolder="" type="text" disabled v-model="baseInfo.applyDate"></u-input>
        </u-form-item>

        <!-- 审批历史开始 -->
        <view v-if="AddOrEdit=='view'">
          <u-gap :marginRight="getGapMarginRowNumber()" :marginLeft="getGapMarginRowNumber()" :height="$theme.cm_section_top_gap_height" :bg-color="$theme.cm_gap_color"></u-gap>
          <form-section title="审批历史"></form-section>
          <u-form-item label="" class="u-m-l-12">
            <flow-his-no-doc :bizUuid="baseInfo.repairRecordUuid" processDefKey="creditRepair" :endTitle="endTitle"></flow-his-no-doc>
          </u-form-item>
        </view>

      </u-form>
    </view>
    <view class="submit-btns btn-other-cls" v-if="!isDisabled">
      <u-button class="u-btn" type="primary" @click="handleSave('1')">保存</u-button>
      <u-button class="u-btn" type="primary" @click="handleSave('2')">提交</u-button>
    </view>
    <u-calendar mode="date" :max-date="yestDate" v-model="isShowRegDate" @change="changeDate('undertakeDate',$event)">
    </u-calendar>
  </view>
</template>

<script>
import mUpload from "@/components/m-upload.vue";
import DicChoice from "@/components/dic_choice.vue";
import formSection from "@/components/form-section.vue";
import creditService from "@/service/check/check.service.js";
import commonService from "@/service/common/common.service.js";
import { M_DAY_PLAN_STATUS } from "@/service/check/mapping/enum.js";
import FlowHisNoDoc from "@/components/flow-his-no-doc.vue";
import { dateUtils } from "@/common/util";
import intelligenceservice from "@/service/intelligence/intelligence.service";
export default {
  components: {
    formSection,
    FlowHisNoDoc,
    DicChoice,
    mUpload
  },
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  onLoad(options) {
    this.AddOrEdit = options.AddOrEdit;
    if (options.repairRecordUuid) {
      this.baseInfo.repairRecordUuid=options.repairRecordUuid
      this.prvParam.bizUuid=options.repairRecordUuid
      this.getRepairRecord(options.repairRecordUuid);
      this.initData()
    }
    if (this.AddOrEdit == "view") {
      this.isDisabled = true;
      this.currentTitle='信用修复查看'
    } else if(this.AddOrEdit == "edit") {
      this.isDisabled = false;
      this.currentTitle='信用修复编辑'
    }else{
      this.isDisabled = false;
      this.currentTitle='信用修复发起'
    }
  },
  data() {
    return {
      currentTitle:'信用修复发起',
      AddOrEdit: "",
      picIds: "10",
      YYapply: this.$store.state.dicts["M_REPAIR_TYPE"].APPLY_REPAIR,
      yestDate: this.$u.timeFormat(Date.now()),
      isShowRegDate: false,
      isDisabled: false,
      prvParam: {
        gfCode :"creditRepair"
      },
      fileList: [],
      baseInfo: {
        licNo: "",
        applicant: "",
        companyName: "",
        businessLicNo: "",
        managerName: "",
        targetName: "",
        repairScore: "",
        repairBeforeCreditLevel: "",
        repairBeforeCreditScore: "",
        retailerUuid: "",
        repairType: "02",
        applyDate: this.$u.timeFormat(Date.now()),
        handlePerson: this.$storage.get(this.$rp.common.USER).user.personName,
        handlePersonUuids: this.$storage.get(this.$rp.common.USER).user
          .personUuid,
        handlePersonAdvice: "",
        targetCode: "",
        standardUuid: "",
        repairAfterCreditLevel: "",
        targetType: "",
        creditLevel: "",
        problemDescription: "",
        checkResult: "",
        birthDate: "",
        personNative: "",
        lossRecordUuid: "",
        status: ""
      },
      dataSource: [],
      scrollRealHeight: "50px",
      bean: {},
      dictList: [
        {
          label: "依申请修复",
          value: "02"
        },
        {
          label: "异议修复",
          value: "03"
        },
        {
          label: "特殊修复",
          value: "04"
        }
      ],
      step: "",
      endTitle: "",
      approvalDisabled: false,
      undertakerIsEdit: true,
      departmentIsEdit: true,
      responsibleIsEdit: true,
      auxiliaryIsEdit: true,
      approveDis: true,
      ifSub: false,
      rules: {
        licNo: [
          {
            required: true,
            message: "请选择许可证号",
            trigger: ["change", "blur"]
          }
        ],
        targetName: [
          {
            required: true,
            message: "请选择涉烟违法违规行为！",
            trigger: ["change", "blur"]
          }
        ],
        problemDescription: [
          {
            required: true,
            message: "请输入问题描述！",
            trigger: ["change", "blur"]
          }
        ],
        checkResult: [
          {
            required: true,
            message: "请输入核查情况！",
            trigger: ["change", "blur"]
          }
        ]
      }
    };
  },

  methods: {
    // 选择审批人
    toSelectPerson(docInsUuid = "") {
      this.$u.route({
        url: "/pages/commonPage/flowUserSelectComponent",
        params: {
          flowFormCode: this.prvParam.gfCode || "creditRepair", // 日计划终止的gfcode
          docInsUuid: docInsUuid // PC 端没传
        }
      });
    },
    changeHeight() {
      this.$nextTick(() => {
        this.$refs.cons.init();
        this.$refs.files.init();
      });
    },
    updateTableHeight() {
      commonService
        .goFiles(this.prvParam.bizUuid, this.$FILE_GROUP_TYPE.m_credit_apply)
        .then(rs => {
          if (rs.success) {
            if (rs.data.length > 0) {
              rs.data.forEach(item => {
                if (typeof item.gfiSize == "number") {
                  item.gfiSize = this.getfilesize(item.gfiSize);
                }
              });
              this.dataSource = rs.data;
              this.dataSource = rs.data;
              if(this.AddOrEdit=='view'){
                setTimeout(() => {
                this.scrollRealHeight =
                  this.$refs.tbRef.$el.clientHeight + 5 + "px";
              }, 100);
              }
              
            }
          } else {
            this.$u.toast(rs.msg);
          }
        })
        .catch(err => {
          this.$modal.hideLoading();
          this.$u.toast(err);
        });
    },
    getfilesize(size) {
      if (!size) return "";
      var num = 1024.0; //byte
      if (size < num) return size + "B";
      if (size < Math.pow(num, 2)) return (size / num).toFixed(2) + "K"; //kb
      if (size < Math.pow(num, 3))
        return (size / Math.pow(num, 2)).toFixed(2) + "M"; //M
      if (size < Math.pow(num, 4))
        return (size / Math.pow(num, 3)).toFixed(2) + "G"; //G
      return (size / Math.pow(num, 4)).toFixed(2) + "T"; //T
    },
    initData() {
    	this.$modal.showLoading('加载中...');
    	creditService.getCreditRepairRecord({repairRecordUuid:this.baseInfo.repairRecordUuid})
    		.then((res) => {
    			this.$modal.hideLoading();
    			if (res.success) {
            this.updateTableHeight(); // 附件上传表格 高度
    				this.bean = res.bean;
    				this.baseInfo = res.bean;

    				this.endTitle = this.bean.status == M_DAY_PLAN_STATUS.TERMINATION ? '结束' : '...';
    				
    			} else {
    				this.$modal.alert(res.msg, () => {
    					this.error();
    				});
    			}
    		})
    		.catch((e) => {
    			this.$modal.hideLoading();
    			this.$modal.alert('加载失败' + e, () => {
    				this.error();
    			});
    		});
    },
    getGapMarginRowNumber() {
      return "-" + this.$theme.cm_content_paddng_row.replace("rpx", "");
    },
    handleGoToRetList() {
      this.$u.route(
        "pages/check/CreditRepairOrigination/components/retailerList"
      );
    },
    handleGoToTobacco() {
      if (!this.baseInfo.repairType) {
        this.$u.toast("请选择修复类型");
        return;
      }
      if (!this.baseInfo.retailerUuid) {
        this.$u.toast("请选择零售户");
        return;
      }
      this.$u.route(
        "pages/check/CreditRepairOrigination/components/TobaccoRelatedViolations",
        {
          repairType: this.baseInfo.repairType,
          retailerUuid: this.baseInfo.retailerUuid,
          YYapply: this.YYapply
        }
      );
    },
    changeDate(type, e) {
      this.baseInfo.applyDate = dateUtils.dateFormat(
        "yyyy-MM-dd",
        new Date(e.result)
      );
    },
    radioGroupChange(value) {
      if (value == "04") {
        let repairReason = this.$store.state.dicts["M_REPAIR_REASON"];
        for (let i = 0; i < repairReason.length; i++) {
          if (repairReason[i].bcbCode == "01") {
            this.baseInfo.problemDescription = repairReason[i].bcbName;
          }
        }
      } else {
        this.baseInfo.problemDescription = "";
      }
      if(this.baseInfo.repairScore){
        this.baseInfo.repairScore = '';
        this.baseInfo.targetName = '';
        this.baseInfo.lossRecordUuid = '';
        this.baseInfo.targetCode ='';
        this.baseInfo.standardUuid = '';
        this.baseInfo.repairAfterCreditLevel ='';
        this.baseInfo.targetType = '';
      }
      this.YYapply = value;
    },
    // 上传/删除图片事件
    changeUpload(list, key) {
      if (list.length > 0) {
        this.fileList = [...list];
      } else {
        this.fileList = [];
      }
    },
    //保存
    handleSave(type) {
      this.$refs.uForm.validate(valid => {
        if (!valid) return;
        if (this.fileList.length > 0) {
          this.baseInfo.fileList = Array.from(new Set(this.fileList));
        }
        if (type == "1") {
          this.baseInfo.status = "00"; //草稿00，提交01
          creditService.saveLicCreditRepairRecord(this.baseInfo).then(res => {
            if (res.success) {
              this.backPrev({
                paramKey: "SaveRefresh",
                param: true
              });
            } else {
              this.$u.error(res.msg);
            }
          });
        } else {
          this.baseInfo.status = "01";
          this.toSelectPerson();
          console.log("提交");
        }
      });
    },
    //获取详情
    getRepairRecord(repairRecordUuid) {
      creditService
        .getCreditRepairRecord({ repairRecordUuid: repairRecordUuid })
        .then(res => {
          if (res.success) {
            Object.keys(this.baseInfo).forEach(key => {
              this.baseInfo[key] =
                res.bean[key] == undefined ? this.baseInfo[key] : res.bean[key];
            });
            let params = {
              bizId: res.bean.repairRecordUuid,
              group: this.$FILE_GROUP_TYPE.m_credit_apply,
              menuCode: null
            };
            intelligenceservice.findFilesByBizIdAndGroup(params).then(res => {
              if (res.success) {
                this.fileList = res.data;
                this.dataSource=res.data;
                if(this.AddOrEdit == "view"){
                  setTimeout(() => {
                  this.scrollRealHeight =
                    this.$refs.tbRef.$el.clientHeight + 5 + "px";
                }, 100);
                }
                
              }
            });
          } else {
            this.$u.error(res.msg);
          }
        });
    },
    goShowRegDate(){
      this.isShowRegDate = true
    },
    // 根据页面返回的参数处理相应逻辑, 方法名updateBackState固定
    updateBackState(param) {
      // 选中的卷烟
      console.log("选中的数据", param);
      console.log(param);
      if (param.flowUserSelectBack) {
        // 选择审批人
        let nextPersons = [];
        for (let fu of param.flowUserSelectBack) {
          nextPersons.push(fu.personId);
        }
        this.baseInfo.nextPersonUuids = nextPersons.join(",");
        creditService.saveLicCreditRepairRecord(this.baseInfo).then(res => {
          if (res.success) {
            this.$u.success("保存成功！");
            this.backPrev({
              paramKey: "SubmitRefresh",
              param: true
            });
          } else {
            this.$u.error(res.msg);
          }
        });
      }
      let paramRetailer = param[this.$rp.check.CHECK_CLIENT][0];
      if (!paramRetailer.standardUuid) {
        this.baseInfo.licNo = paramRetailer.licNo;
        this.baseInfo.applicant = paramRetailer.managerName;
        this.baseInfo.companyName = paramRetailer.companyName;
        this.baseInfo.businessLicNo = paramRetailer.businessLicNo;
        this.baseInfo.managerName = paramRetailer.managerName;
        // this.baseInfo.targetName=paramRetailer.targetName
        // this.baseInfo.repairScore=paramRetailer.repairScore
        this.baseInfo.repairBeforeCreditLevel = paramRetailer.creditLevel;
        this.baseInfo.creditLevel = paramRetailer.creditLevel;
        this.baseInfo.repairBeforeCreditScore = paramRetailer.creditScore;
        this.baseInfo.retailerUuid = paramRetailer.retailerUuid;
        console.log(this.baseInfo);
      } else {
        this.baseInfo.repairScore = paramRetailer.creditScore;
        this.baseInfo.targetName = paramRetailer.targetName;
        this.baseInfo.lossRecordUuid = paramRetailer.lossRecordUuid;
        this.baseInfo.targetCode = paramRetailer.targetCode;
        this.baseInfo.standardUuid = paramRetailer.standardUuid;
        this.baseInfo.repairAfterCreditLevel =
          paramRetailer.repairAfterCreditLevel;
        this.baseInfo.targetType = paramRetailer.targetType;
        console.log(paramRetailer);
      }
    }
  },
  error() {
    uni.navigateBack();
  }
};
</script>

<style scoped lang="scss">
.page {
  padding: 0;
}

.sub-title {
  background: #f5f5f5;
  color: #989ea1;
  font-size: 24rpx;
  border-radius: 4px;
  margin-right: 10px;
  padding: 4px 8px;
}

.f-ctn {
  width: 100%;
}

.tb-lay {
  width: 900px;
  margin-left: 1px;
  margin-right: 1px;
}

.content {
  padding-left: $cm-content-paddng-row;
  padding-right: $cm-content-paddng-row;
  padding-top: $cm-conent-padding-column;
  padding-bottom: 70px;
}

.td-text {
  word-break: break-all;
  word-wrap: break-word;
}

/deep/.u-td {
  height: auto;
}
</style>